<template>
  <div class="bank-withdraw-container">
    <ResponsiveNav />
    <div class="header-placeholder"></div>

    <div class="page-content">
      <div class="bank-withdraw-page">
        <!-- 面包屑导航区域 -->
        <div class="page-nav">
          <div class="breadcrumb">
            <el-breadcrumb separator="/">
              <el-breadcrumb-item :to="{ path: '/assets' }">
                <i class="fas fa-chevron-left"></i> {{ $t('返回资产') }}
              </el-breadcrumb-item>
              <el-breadcrumb-item>{{ $t('银行卡提款') }}</el-breadcrumb-item>
            </el-breadcrumb>
          </div>
          <div class="divider"></div>
        </div>

        <!-- 页面标题 -->
        <div class="page-header">
          <h1>{{ $t('银行卡提款') }}</h1>
        </div>

        <!-- 提款表单 -->
        <div class="withdraw-form-card">
          <!-- 未绑定银行卡提示 -->
          <div v-if="!hasBankCard" class="no-bank-card">
            <i class="fas fa-credit-card"></i>
            <p>{{ $t('您还未绑定银行卡') }}</p>
            <el-button type="primary" @click="goToBankManage">
              {{ $t('去绑定银行卡') }}
            </el-button>
          </div>

          <!-- 有银行卡时显示表单 -->
          <el-form
            v-else
            ref="formRef"
            :model="form"
            :rules="rules"
            label-position="top"
          >
            <!-- 选择银行卡 -->
            <el-form-item  :label="$t('选择银行卡')" prop="bankCardId">
              <div class="bank-card-list">
                <div
                  v-for="card in bankCards"
                  :key="card.id"
                  :class="['bank-card-item', { active: form.bankCardId === card.id }]"
                  @click="selectCard(card)"
                >
                  <div class="card-info">
                    <!-- <img :src="card.bankIcon" :alt="card.bankName" class="bank-icon"> -->
                    <div class="bank-details">
                      <div class="bank-name">{{ card.bankName }}</div>
                      <div class="card-number"> **** **** ****{{ card.bankCardNumber.slice(-4) }}</div>
                    </div>
                  </div>
                  <div class="radio-wrapper">
                    <div class="custom-radio"></div>
                  </div>
                </div>
              </div>
            </el-form-item>

            <!-- 提款金额 -->
            <el-form-item :label="$t('提款金额')" prop="amount">
              <el-input
                v-model.number="form.amount"
                type="number"
                :placeholder="$t('请输入提款金额')"
              >
                <!-- <template #prefix>¥</template> -->
              </el-input>
              <div class="balance-info">
                {{ $t('可用余额') }}: <span class="amount">{{ formatPrice(balance*langStore.languageRate) }}</span>
                <span class="unit">{{ langStore.languageSymbol }}</span>
                <el-button type="primary" link @click="setMaxAmount">{{ $t('全部提取') }}</el-button>
              </div>
            </el-form-item>

            <!-- 资金密码 -->
            <el-form-item :label="$t('资金密码')" prop="fundPassword">
              <el-input
                v-model="form.fundPassword"
                type="password"
                :placeholder="$t('请输入资金密码')"
                show-password
              />
            </el-form-item>

            <!-- 提交按钮 -->
            <el-form-item>
              <el-button
                type="primary"
                class="submit-button"
                :loading="loading"
                @click="handleSubmit"
              >
                {{ $t('确认提款') }}
              </el-button>
            </el-form-item>
          </el-form>
        </div>

        <!-- 温馨提示 -->
        <div class="notice-card">
          <h3><i class="fas fa-info-circle"></i> {{ $t('温馨提示') }}</h3>
          <ul>
            <!-- <li>{{ $t('单笔提款金额限制：100-50000元') }}</li>
            <li>{{ $t('每日提款次数限制：5次') }}</li> -->
            <li>{{ $t('提款手续费：免费') }}</li>
            <li>{{ $t('预计到账时间：工作日10分钟内，节假日可能延长') }}</li>
          </ul>
        </div>
      </div>
    </div>

    <Footer />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { useRouter } from 'vue-router'
import ResponsiveNav from '@/components/ResponsiveNav.vue'
import Footer from '@/components/Footer.vue'
import {useI18n} from "vue-i18n";
const { t } = useI18n();
import {  getbankList,ApiWithdrawSubmit} from '@/api/assets'

import useUserStore from '@/store/modules/user'
const userStore = useUserStore()
import useLangStore from '@/store/modules/lang'
const langStore = useLangStore()

const router = useRouter()
const formRef = ref<FormInstance>()
const loading = ref(false)
const balance = ref(10000)

interface WithdrawForm {
  bankCardId: string | number
  amount: string | number
  fundPassword: string
}

interface BankCard {
  id: number
  bankName: string
  bankIcon: string
  lastFourDigits: string
  isDefault: boolean
}

// 表单数据
const form = reactive<WithdrawForm>({
  bankCardId: '',
  amount: '',
  fundPassword: ''
})
// 工具方法
const formatPrice = (price) => {
  // 转为数字后再调用 toFixed
  if (!isNaN(price)) {
    price = Number(price);
    return price.toFixed(2)
  } else {
    return 0
  }
}

//获取个人信息
const getInfouser = async () => {
  const getInfouserStore = await userStore.getInfo();
  balance.value = getInfouserStore.data?.wallet?.memberWallet || 0;
    //获取提款地址
    let obj = {
      pageSize:"10",
      pageNum:'1'
    }

    // //获取默认提款银行地址;
    getbankList(obj).then(res => {
      bankCards.value = res.rows;
      // form.value = {
      //   // crypto: 'USDT',
      //   withdrawWay: 2,
      //   address: res.data.walletAddress,
      //   applyMoney: 0,
      //   coin: res.data.coinName,
      //   withdrawPwd: ''

      // }
    })

}
onMounted(() => {
  getInfouser();

})
// 表单验证规则
const rules: FormRules = {
  bankCardId: [
    { required: true, message: t('请选择银行卡'), trigger: 'change' }
  ],
  amount: [
    { required: true, message: t('请输入提款金额'), trigger: 'blur' },
    { type: 'number', message: t('金额必须为数字'), trigger: 'blur' },
    // { min: 100, message: t('最小提款金额为100元'), trigger: 'blur' },
    // { max: 50000, message: t('最大提款金额为50000元'), trigger: 'blur' }
  ],
  fundPassword: [
    { required: true, message: t('请输入资金密码'), trigger: 'blur' },
    { min: 6, max: 6, message: t('资金密码为6位数字'), trigger: 'blur' }
  ]
}

// 银行卡列表
const bankCards = ref<BankCard[]>([])

// 获取银行卡列表
const fetchBankCards = async () => {
  try {
    // TODO: 这里应该调用API获取银行卡列表
    // 临时模拟数据
    bankCards.value = [
      // {
      //   id: 1,
      //   bankName: '中国工商银行',
      //   bankIcon: '/images/banks/icbc.png',
      //   lastFourDigits: '8888',
      //   isDefault: true
      // },
    ]
  } catch (error) {
    // console.error('获取银行卡列表失败:', error)
  }
}

// 页面加载时获取银行卡列表
onMounted(() => {
  fetchBankCards()
})

// 检查是否有绑定银行卡
const hasBankCard = computed(() => bankCards.value.length > 0)

// 跳转到银行卡管理页面
const goToBankManage = () => {
  router.push('/account/bank?from=withdraw')
}

// 选择银行卡
const selectCard = (card: BankCard) => {
  form.bankCardId = card.id
}

// 设置最大提款金额
const setMaxAmount = () => {
  form.amount = balance.value
}

// 提交表单
const handleSubmit = async () => {
  
  if (!formRef.value) return
  let obj = {
    
    // bankName:bankCards.value[0].bankName,//银行名称
    // bankCardNo:bankCards.value[0].bankCardNumber,//银行卡号
    memberBankAddressId:bankCards.value[0].id,
    applyMoney:form.amount,//申请提现金额
    withdrawPwd:form.fundPassword,//资金密码
    withdrawWay:1
    
  }
  try {
    await formRef.value.validate()
    loading.value = true

    // TODO: 调用提款API
    await new Promise(resolve => setTimeout(resolve, 1000))
    ApiWithdrawSubmit(obj).then(res=>{
      if(res.code == 200 ){
        ElMessage.success(t('提款申请已提交'))
        router.push('/assets')
      }
    })
    
  } catch (error: any) {
    ElMessage.error(error.message || t('提交失败'))
  } finally {
    loading.value = false
  }
}
</script>

<style lang="scss" scoped>
.bank-withdraw-container {
  background-color: #fff;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.bank-withdraw-page {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
  width: 100%;
}

.withdraw-form-card {
  background: #fff;
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 24px;
  margin-bottom: 24px;
}

.bank-card-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.bank-card-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border: 1px solid #ddd;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;

  &:hover {
    border-color: var(--el-color-primary);
  }

  &.active {
    border-color: var(--el-color-primary);
    background-color: var(--el-color-primary-light-9);

    .custom-radio {
      border-color: var(--el-color-primary);
      background-color: var(--el-color-primary);

      &::after {
        content: '';
        position: absolute;
        width: 6px;
        height: 6px;
        border-radius: 50%;
        background-color: #fff;
      }
    }
  }
}

.card-info {
  display: flex;
  align-items: center;
  gap: 12px;

  .bank-icon {
    width: 32px;
    height: 32px;
  }

  .bank-details {
    .bank-name {
      font-weight: 500;
      margin-bottom: 4px;
    }

    .card-number {
      color: #666;
      font-size: 13px;
    }
  }
}

.custom-radio {
  width: 16px;
  height: 16px;
  border: 1px solid #ddd;
  border-radius: 50%;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}

.balance-info {
  margin-top: 8px;
  color: #666;
  font-size: 13px;
  display: flex;
  align-items: center;
  gap: 8px;

  .amount {
    color: #333;
    font-weight: 500;
  }
}

.submit-button {
  width: 100%;
  margin-top: 24px;
}

.notice-card {
  background: #fafafa;
  border-radius: 8px;
  padding: 20px;

  h3 {
    color: #333;
    font-size: 16px;
    margin-bottom: 16px;
    display: flex;
    align-items: center;
    gap: 8px;

    i {
      color: #0066c0;
    }
  }

  ul {
    list-style: none;
    padding: 0;
    margin: 0;
    color: #666;
    font-size: 14px;

    li {
      margin-bottom: 8px;
      padding-left: 16px;
      position: relative;

      &::before {
        content: '•';
        position: absolute;
        left: 0;
        color: #999;
      }

      &:last-child {
        margin-bottom: 0;
      }
    }
  }
}

.page-header {
  margin: 12px 0 20px;

  h1 {
    font-size: 24px;
    color: #111;
    font-weight: 500;
  }
}

.no-bank-card {
  text-align: center;
  padding: 40px 0;
  color: #666;

  i {
    font-size: 48px;
    color: #999;
    margin-bottom: 16px;
  }

  p {
    font-size: 16px;
    margin-bottom: 20px;
  }
}

@media (max-width: 768px) {
  .bank-withdraw-page {
    padding: 16px;
  }

  .withdraw-form-card {
    padding: 16px;
  }

  .bank-card-item {
    padding: 12px;
  }
}
</style>
